package com.jichangxiu.flow.server.core.parser.impl;

import cn.hutool.core.util.ObjectUtil;
import com.jichangxiu.flow.server.core.context.LiteFlowContext;
import com.jichangxiu.flow.server.core.entity.Bo.ElBo;
import com.jichangxiu.flow.server.core.entity.Bo.NodeBo;
import com.jichangxiu.flow.server.core.entity.Bo.ProcessBo;
import com.jichangxiu.flow.server.core.entity.dto.LogicFlow;
import com.jichangxiu.flow.server.core.parser.LogicFlowParser;
import com.jichangxiu.flow.server.core.utils.TreeUtils;

import java.util.List;

/**
 * LiteFlowParser:
 *
 * @author Jcx
 * @create 2025-01-01 00:00:00
 */
public class LiteFlowParser implements LogicFlowParser {

    private LiteFlowContext liteFlowContext;

    public LiteFlowParser(LogicFlow logicFlow) {
        // 构建上下文
        this.liteFlowContext = LiteFlowContext.buildLogicFlowContext(logicFlow.getNodes(), logicFlow.getEdges());
    }

    @Override
    public ElBo extractElBo() {
        // 构建业务节点树对象
        NodeBo rootNodeBo = TreeUtils.buildNodeBoTree(this.liteFlowContext, true);
        if (ObjectUtil.isEmpty(rootNodeBo)) throw new RuntimeException("构建逻辑流程节点树失败");
        TreeUtils.setNodeBoParentId(rootNodeBo);
        this.liteFlowContext.setRootNodeBo(rootNodeBo);
        List<ProcessBo> processBoList = TreeUtils.buildProcessBoList(ObjectUtil.cloneByStream(rootNodeBo));
        if (ObjectUtil.isEmpty(processBoList)) throw new RuntimeException("构建逻辑流程链路失败");
        return ElBo.buildElBo(this.liteFlowContext, processBoList);
    }

}
